package com.duke.shaking.net;

import org.apache.http.conn.ConnectTimeoutException;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.util.Log;
import android.widget.Toast;

import com.duke.shaking.ResultCodeFactory;
import com.loopj.android.http.AsyncHttpResponseHandler;

/**
 * The class to handle respose with "result" in it
 * @author xiaomin
 *
 */
public class AsyncHttpResponseWithResultHandler extends AsyncHttpResponseHandler {
	public static final String TAG = "AsyncHttpResponseWithResultHandler";
	
	private ProgressDialog progressDialog;
	
	public String getResult(String strJson) {
		try {
			JSONObject jsonObj = new JSONObject(strJson);
			JSONObject headerJson = jsonObj.optJSONObject(NetUtils.HEADER);
			if(headerJson != null) {
				return headerJson.optString(NetUtils.RESULT);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	public JSONObject getBody(String strJson) {
		try {
			JSONObject jsonObj = new JSONObject(strJson);
			return jsonObj.optJSONObject(NetUtils.BODY);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
	}

	@Override
	public void onFailure(Throwable arg0, String arg1) {
		// TODO Auto-generated method stub
		super.onFailure(arg0, arg1);
		if (progressDialog != null && progressDialog.isShowing()) {
			progressDialog.dismiss();
			progressDialog = null;
		}
		/*if(arg0 != null && arg0.getCause() != null) {
			// timeout
			if(arg0.getCause() instanceof ConnectTimeoutException) {
			}
		}*/
		if (arg0 != null && arg0.getCause() != null) {
			Log.i(TAG, "Failure message: " + arg0.getCause().getLocalizedMessage());
		}
		else {
			Log.i(TAG, "Failure message");
		}
	}

	@Override
	public void onSuccess(int arg0, String arg1) {
		// TODO Auto-generated method stub
		super.onSuccess(arg0, arg1);
		Log.i(TAG, "---- request success ----");
		Log.i(TAG, "status code:" + arg0);
		Log.i(TAG, "response:" + arg1);
		if (progressDialog != null && progressDialog.isShowing()) {
			progressDialog.dismiss();
			progressDialog = null;
		}
		String re = getResult(arg1);
		if(ResultCodeFactory.SUCCESS.equals(re)) {
			onResultSuccess(arg1);
		} else {
			onResultFailure(re);
		}
	}
	
	/**
	 * Callback if result is success
	 * @param response The response from server
	 */
	public void onResultSuccess(String response) {
		
	}
	
	/**
	 * Callback if result is not success
	 */
	public void onResultFailure(String result) {
		Log.i(TAG, "result = " + result);
	}

	public ProgressDialog getProgressDialog() {
		return progressDialog;
	}

	public void setProgressDialog(ProgressDialog progressDialog) {
		this.progressDialog = progressDialog;
	}
	
}
